package tomkitty.server;

import tomkitty.turdlet.*;
import tomkitty.util.*;
import java.util.*;
import java.io.*;

public class ConnectionHandlerPool {

	private Stack<ConnectionHandler> waiting = new Stack<ConnectionHandler>();
	private Vector<ConnectionHandler> running = new Vector<ConnectionHandler>();
	private int minthreads;
	private int maxthreads;
	private static Object lock = new Object();

	public ConnectionHandlerPool(int min, int max) {
		minthreads = min;
		maxthreads = max;

		waiting.ensureCapacity(minthreads);
		running.ensureCapacity(maxthreads);

		for (int i = 0; i < minthreads; i++) {
			ConnectionHandler h = new ConnectionHandler();
			h.setPool(this);
			h.start();
			waiting.push(h);
		}
	}

	public synchronized ConnectionHandler getConnectionHandler() {
		ConnectionHandler h = null;

		if (running.size() < maxthreads) {
			if (waiting.isEmpty()) {
				h = new ConnectionHandler();
				h.setPool(this);
				h.start();
			} else {
				h = waiting.pop();
			}

			running.add(h);
		} else {
			System.out.println("Too many threads.");
		}

		return h;
	}

	public synchronized void recycle(ConnectionHandler h) {
		running.remove(h);

		if (waiting.size() < minthreads) {
			waiting.push(h);
		}
	}

}
